<template>
  <view class="container">
    <view class="header">
      <text class="title">我的钱包</text>
    </view>
    
    <view class="balance-section">
      <view class="balance-info">
        <text class="label">当前钱包余额</text>
        <text class="amount">¥{{ balance.toFixed(2) }}</text>
        <text class="note">当前钱包金额通常将在三天内进行打款</text>
      </view>
      
      <view class="action-buttons">
        <button class="recharge-button" @tap="handleRecharge">
          <text class="iconfont">💰</text>
          <text class="button-text">零钱充值</text>
        </button>
        <button class="withdraw-button" @tap="handleWithdraw">
          <text class="iconfont">💸</text>
          <text class="button-text">现金提现</text>
        </button>
      </view>
    </view>
    
    <view class="transaction-list">
      <view class="section-title">交易记录</view>
      
      <view v-if="transactionList.length > 0" class="list-content">
        <view 
          v-for="(item, index) in transactionList" 
          :key="index" 
          class="transaction-item"
        >
          <view class="transaction-info">
            <text class="store-name">{{ item.storeName }}</text>
            <text class="description" v-if="item.description">{{ item.description }}</text>
            <text class="time">{{ item.time }}</text>
          </view>
          <text 
            class="amount" 
            :class="item.type === 'income' ? 'income' : 'expense'"
          >
            {{ item.amount }}
          </text>
        </view>
      </view>

      <view v-else class="empty-state">
        <uni-icons type="list" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无交易记录</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { getUserWallet, getWalletLog } from '@/api/auth';

const userStore = useUserStore();

// 钱包数据接口
interface WalletInfo {
  walletId: string;
  customerId: string;
  balance: number;
  createdAt: string;
  updatedAt: string;
}

// 交易记录接口
interface TransactionItem {
  type: 'income' | 'expense';
  amount: string;
  storeName: string;
  description: string;
  time: string;
}

// 钱包余额
const balance = ref(0);
const walletId = ref('');

// 交易记录列表
const transactionList = ref<TransactionItem[]>([]);

// 加载钱包信息
const loadWalletInfo = async () => {
  if (!userStore.userInfo?.customerId) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  try {
    const data = await getUserWallet(userStore.userInfo.customerId) as WalletInfo;
    
    console.log('钱包信息返回:', data);
    
    if (data) {
      balance.value = data.balance || 0;
      walletId.value = data.walletId;
      
      // 获取交易记录
      if (data.walletId) {
        loadTransactionList(data.walletId);
      }
    }
  } catch (error) {
    console.error('获取钱包信息失败:', error);
  }
};

// 加载交易记录
const loadTransactionList = async (wId: string) => {
  if (!userStore.userInfo?.customerId) return;

  try {
    const data = await getWalletLog(userStore.userInfo.customerId, Number(wId));
    
    console.log('交易记录返回:', data);
    
    // 后端返回的是数组
    if (data && Array.isArray(data)) {
      transactionList.value = data.map((item: any) => ({
        type: (item.amount && item.amount > 0) ? 'income' : 'expense',
        amount: item.amount > 0 ? `+${Number(item.amount).toFixed(2)}` : Number(item.amount).toFixed(2),
        storeName: item.description || '交易',
        description: item.remark || '',
        time: formatTime(item.createdAt)
      }));
    } else {
      transactionList.value = [];
    }
  } catch (error) {
    console.error('获取交易记录失败:', error);
    transactionList.value = [];
  }
};

// 格式化时间
const formatTime = (dateStr: string): string => {
  if (!dateStr) return '';
  try {
    const date = new Date(dateStr);
    return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  } catch (error) {
    return '';
  }
};

// 处理充值
const handleRecharge = () => {
  uni.showToast({
    title: '充值功能开发中',
    icon: 'none'
  });
};

// 处理提现
const handleWithdraw = () => {
  uni.showToast({
    title: '提现功能开发中',
    icon: 'none'
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadWalletInfo();
});
</script>

<style scoped>
.container {
  height: 100vh;
  background-color: #f8f8f8;
}

.header {
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  background-color: #fff;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.balance-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.balance-info {
  text-align: center;
  margin-bottom: 30rpx;
}

.label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.amount {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin: 20rpx 0;
}

.note {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  gap: 20rpx;
}

.recharge-button,
.withdraw-button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 180rpx;
  height: 60rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  border: none;
}

.recharge-button {
  background-color: #00C853;
  color: #fff;
}

.withdraw-button {
  background-color: #f5f5f5;
  color: #666;
}

.iconfont {
  margin-right: 10rpx;
  font-size: 24rpx;
}

.transaction-list {
  flex: 1;
  padding: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.list-content {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.transaction-item:last-child {
  border-bottom: none;
}

.transaction-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.store-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.description {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.time {
  font-size: 24rpx;
  color: #999;
}

.amount {
  font-size: 32rpx;
  font-weight: bold;
  margin-left: 20rpx;
}

.amount.income {
  color: #00C853;
}

.amount.expense {
  color: #ff3b30;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  background-color: #fff;
  border-radius: 16rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-top: 20rpx;
}
</style>